import { produce } from "immer";
import { createStore } from "redux";
import { composeWithDevTools } from "@redux-devtools/extension";

const initialState = {
  todos: [
    {
      id: 1,
      title: "吃饭",
      done: true,
    },
    {
      id: 2,
      title: "睡觉",
      done: false,
    },
  ],
};

const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    // { type: "TOGGLE", id: 1 }
    case "TOGGLE":
      // 1. 修改了源数据，是不OK的
      // const index = state.todos.findIndex((item) => item.id === action.id);
      // state.todos[index].done = !state.todos[index].done;
      // return state;

      // 2. 修改没问题，但是写起来太麻烦了
      // return {
      //   ...state,
      //   todos: state.todos.map((todo) => {
      //     if (todo.id === action.id) {
      //       return {
      //         ...todo,
      //         done: !todo.done,
      //       };
      //     } else {
      //       return todo;
      //     }
      //   }),
      // };

      // 3. 使用 immer 来简化修改
      return produce(state, (draft) => {
        // 针对 draft 直接修改即可
        // 1. 直接找到要修改的哪一项todo
        const todo = draft.todos.find((todo) => todo.id === action.id)!;
        // 2. 直接对查找到的 todo 做修改
        todo.done = !todo.done;
      });
    default:
      return state;
  }
};

const store = createStore(rootReducer, composeWithDevTools());

export default store;
